#include "gsquare.h"
#include "MinMax.h"

GSquare::GSquare(QWidget *parent) :
    QWidget(parent)
{
    scene = NULL;
    fond = NULL;
    vw_square = NULL;
    nb_col = 19;
    j1 = NULL;
    j2 = NULL;
    current_player_img = NULL;
    current_player = 0;
    proxy_score = NULL;
    bt_time = 1;
    _timeIa = 50;
    flag_opt = 0;
}

GSquare::~GSquare()
{
    if (scene != NULL)
        delete scene;
    if (fond != NULL)
        delete fond;
    if (vw_square != NULL)
        delete vw_square;
}

const void GSquare::createMenu()
{
    this->setMinimumSize(800, 600);
    this->setMaximumSize(800, 600);

    // Creer la scene
    scene = new QGraphicsScene(this);


    // Creer le fond
    QPixmap pix = QPixmap("fond.png", "PNG");
    fond = new QGraphicsPixmapItem(pix, NULL, scene);

    //  qreal scale = (qreal)((800.0 - pix.size().height()) / /*(pix.size().width())*/ 1000);
    qreal scale = 0.62;
    fond->setScale(scale);


    // Creer la vue
    this->vw_square = new QGraphicsView(scene);
    this->vw_square->setBaseSize(900, 700);
    this->vw_square->setMaximumSize(900, 700);
    this->vw_square->setMinimumSize(900, 700);

    QTransform matrice;
 //   matrice.rotateRadians(-40, Qt::XAxis);
//    matrice.translate(100, 100,     );
   // matrice.scale(1.2, 1.2);
    this->vw_square->setTransform(matrice, true);
    this->vw_square->show();

    //Boutton menu
    menu_btn = new QPushButton(NULL);
    menu_btn->setIcon(QIcon("ButtonPlay.png"));
    menu_btn->setFlat(true);
    menu_btn->setAutoFillBackground(false);
//    menu_btn->setTaken(false);
    menu_btn->setGeometry(QRect(800 / 2 - 100, 600 / 2 - 50, 200, 100));
    menu_btn->setIconSize(QSize(200, 100));
    proxy_btn = new QGraphicsProxyWidget(fond);
    proxy_btn->setWidget(menu_btn);
    proxy_btn->setPalette(QPalette(QColor(0, 0, 0, 0)));
    QObject::connect(menu_btn, SIGNAL(released()), this, SLOT(play()));
    QObject::connect(menu_btn, SIGNAL(pressed()), this, SLOT(changeIcon()));


        // bouton option du debut
        menu_opt = new QPushButton(NULL);
        menu_opt->setIcon(QIcon("ButtonOptions.png"));
        menu_opt->setFlat(true);
        menu_opt->setAutoFillBackground(false);
    //    menu_btn->setTaken(false);
        menu_opt->setGeometry(QRect(800 / 2 - 100, 600 / 2 + 100, 200, 100));
        menu_opt->setIconSize(QSize(200, 100));
        proxy_opt = new QGraphicsProxyWidget(fond);
        proxy_opt->setWidget(menu_opt);
        proxy_opt->setPalette(QPalette(QColor(0, 0, 0, 0)));
        QObject::connect(menu_opt, SIGNAL(released()), this, SLOT(option()));
        QObject::connect(menu_opt, SIGNAL(pressed()), this, SLOT(changeIconOption()));

    //creation du bouton quit
        menu_quit = new QPushButton;
        menu_quit->setIcon(QIcon("ButtonQuit.png"));
        menu_quit->setFlat(true);
        menu_quit->setGeometry(QRect(800 / 2 - 100, 600 / 2 + 200, 200, 100));
        menu_quit->setIconSize(QSize(200, 100));
        proxy_menuQuit = new QGraphicsProxyWidget(fond);
        proxy_menuQuit->setWidget(menu_quit);
        proxy_menuQuit->setPalette(QPalette(QColor(0,0,0,0)));

   QObject::connect(menu_quit, SIGNAL(pressed()), this, SLOT(changeIconQuit()));
   QObject::connect(menu_quit,SIGNAL(clicked()), qApp, SLOT(quit()));

}

void GSquare::option()
{
    this->hideMenu();
    if (flag_opt == 0)
        this->createOptions();
    else
    {
        bool ok;
             QString text = QInputDialog::getText(this, tr("QInputDialog::getText()"),
                                                  tr("Choose IA time (10,20,50)"), QLineEdit::Normal,
                                                  QDir::home().dirName(), &ok);
             if (ok && !text.isEmpty())
             {
                 if (text == "50")
                    _timeIa = 50;
                    else if (text == "20")
                     _timeIa = 20;
                     else if (text == "10")
                     _timeIa = 10;
             }
             menu_quit->setHidden(false);
             menu_opt->setHidden(false);

    }
}

void GSquare::createOptions()
{
    QPixmap time_img("IAOption.png");
    item_time = new QGraphicsPixmapItem(time_img, NULL, scene);
    item_time->setPos(20, 600 / 2 - 60);
    item_time->setScale(0.5);

    menu_optIa = new QPushButton(NULL);
    menu_optIa->setIcon(QIcon("IA10Selected.png"));
    menu_optIa->setFlat(true);
    menu_optIa->setAutoFillBackground(false);
//    menu_btn->setTaken(false);
    menu_optIa->setGeometry(QRect(800 / 2 - 100, 600 / 2 + 100, 200, 100));
    menu_optIa->setIconSize(QSize(200, 100));
    proxy_optIa = new QGraphicsProxyWidget(fond);
    proxy_optIa->setWidget(menu_optIa);
    proxy_optIa->setPalette(QPalette(QColor(0, 0, 0, 0)));
    QObject::connect(menu_optIa, SIGNAL(clicked()), this, SLOT(timeIa()));

    menu_optQuit = new QPushButton(NULL);
    menu_optQuit->setIcon(QIcon("ButtonQuit.png"));
    menu_optQuit->setFlat(true);
    menu_optQuit->setAutoFillBackground(false);
//    menu_btn->setTa@ken(false);
    menu_optQuit->setGeometry(QRect(800 / 2 - 100, 600 / 2 + 200, 200, 100));
    menu_optQuit->setIconSize(QSize(200, 100));
    proxy_optQuit = new QGraphicsProxyWidget(fond);
    proxy_optQuit->setWidget(menu_optQuit);
    proxy_optQuit->setPalette(QPalette(QColor(0, 0, 0, 0)));
    QObject::connect(menu_optQuit, SIGNAL(clicked()), this, SLOT(quitOpt()));

}

void GSquare::hideOption()
{
    if (item_time)
        item_time->setVisible(false);
    if (menu_optIa)
        menu_optIa->setHidden(true);
    if (menu_optQuit)
        menu_optQuit->setHidden(true);

}

void GSquare::quitOpt()
{

        this->hideOption();
        this->showMenu();
}

void    GSquare::quitGame()
{

}

void GSquare::timeIa()
{

        if (bt_time == 3)
         bt_time = 1;
        else
            bt_time++;
        if (bt_time == 1)
        {
            menu_optIa->setIcon(QIcon("IA10Selected.png"));
        _timeIa = 10;
            }
        else if (bt_time == 2)
        {
            _timeIa = 20;
            menu_optIa->setIcon(QIcon("IA20Selected.png"));
        }
       else if (bt_time == 3)
        {
             menu_optIa->setIcon(QIcon("IA50Selected.png"));
            _timeIa = 50;
        }

}




void GSquare::showMenu()
{
//    if (menu_optIa)
//        menu_optIa->setHidden(false);
    if (menu_btn)
        menu_btn->setHidden(false);
    if (menu_opt)
        menu_opt->setHidden(false);
    if (menu_quit)
        menu_quit->setHidden(false);

}

void GSquare::hideMenu()
{
//    if (menu_optIa)
//        menu_optIa->setHidden(true);
    if (menu_btn)
        menu_btn->setHidden(true);
    if (menu_opt)
        menu_opt->setHidden(true);
    if (menu_quit)
        menu_quit->setHidden(true);


}



void GSquare::changeIconQuit()
{
    proxy_menuQuit->setPalette(QPalette(QColor(0, 0, 0, 0)));
    menu_quit->setIcon(QIcon("ButtonQuitPushed.png"));
}

void GSquare::changeIconOption()
{
    menu_opt->setIcon(QIcon("ButtonOptionsPushed.png"));
}


void GSquare::changeIcon()
{
    proxy_btn->setPalette(QPalette(QColor(0, 0, 0, 0)));
    menu_btn->setIcon(QIcon("ButtonPlayPushed.png"));
}

void GSquare::play()
{
    this->hideMenu();
    this->createMySquare();
}

void GSquare::displayOptionGame()
{

    this->menu_quit->setHidden(false);
    this->menu_opt->setHidden(false);
    menu_opt->setGeometry(QRect(1000, 750, 200, 100));
    menu_quit->setGeometry(QRect(1000, 850, 200, 100));

}



const void GSquare::createMySquare()
{
    // Window

    // Creer les bouttons + Case
    group_pions = new QButtonGroup(this);

    flag_opt = 1;
    displayOptionGame();
    for (int y = 0; y < nb_col; ++y)
    {
        for (int x = 0; x < nb_col; ++x)
        {
            // Creer la case
            if (x < nb_col - 1 && y < nb_col - 1)
            {
                QPixmap tmp_pix("case.png");
                QGraphicsPixmapItem *pix = new QGraphicsPixmapItem(tmp_pix, fond, scene);
                pix->setPos( 50 + x * 50, 50 + y * 50);
                pix->scale(1.1, 1.1);

				
			}

			// Creer le Bouton
			GCase *btn = new GCase(NULL, x, y);
			btn->setGeometry(25 + x * 50, 25 + y * 50, 50, 50);
			btn->setFlat(true);
			btn->setAutoFillBackground(false);
			btn->setTaken(false);

			group_pions->addButton(btn, x * 100 + y);
           
			QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(fond);
			proxy->setWidget(btn);
			proxy->setPalette(QPalette(QColor(0, 0, 0, 0)));
		}
	  }
	 QObject::connect(group_pions, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(button_released(QAbstractButton *)));
}

const void GSquare::createPlayers()
{
    j1 = new PlayerManager(true);
    j2 = new PlayerManager(true);
}



const void GSquare::setFond(QPixmap *pixmap)
{
    if (fond != NULL)
    {
        scene->removeItem(fond);
        delete fond;
    }
    fond = scene->addPixmap(*pixmap);
    vw_square->update();
}

void GSquare::check_result(int result)
{
    return;
}

void GSquare::change_currentPlayer()
{
    if (!current_player_img) {
    QPixmap player("StartMenuJ1Selected.png");
    current_player_img = new QGraphicsPixmapItem(player, NULL, scene);
    current_player_img->setPos(800 - 200, 600 / 2 - 60);
    current_player_img->setScale(0.5);
}
    if (!proxy_score)
    {
        proxy_score = new QGraphicsTextItem(fond, scene);
        char sc= info.getScore()[0];
        int sc_value;
        for (int i = 0; i < 255; ++i)
            if (i == sc) {
                sc_value = i;
                break;
            }
        QString str = QString();
        str.append(QString("%1").arg(sc_value));
        proxy_score->setPlainText(str);
        proxy_score->setPos(800 - 100, 600 / 2 - 60);
        proxy_score->setDefaultTextColor(QColor(255, 255, 255, 255));
    }

    if (current_player == 0)
        ++current_player;
    else
        --current_player;

    if (current_player == 0)
       {
        current_player_img->setPixmap(QPixmap("StartMenuJ1Selected.png"));
       }
    else
    {
        current_player_img->setPixmap(QPixmap("StartMenuJ2Selected.png"));
    }
}



void GSquare::change_btn_state(GCase *tmp_btn)
{
    QIcon ico;
    if (current_player == 0)
    {
        QPixmap pix("pion_rouge.png");
        pix.scaled(2, 2);
        ico.addPixmap(pix);
    }
    else
    {
        QPixmap pix("pion_noir.png");
        pix.scaled(2, 2);
        ico.addPixmap(pix);
    }

	if (this->info.getCList().empty() == false)
	{
		std::list<coord_t>::iterator	it;
		GCase* c;

		for (it = this->info.getCList().begin(); it != this->info.getCList().end(); it++)
			if ((c = static_cast<GCase*>(group_pions->button(it->x * 100 + it->y))) != NULL)
				c->setTaken(false);
		this->info.getCList().clear();
		int co = this->info.getCList().size();
	}

    ico.actualSize(QSize(tmp_btn->size().width() *2, tmp_btn->size().height() + 2));
    tmp_btn->setIcon(ico);
    tmp_btn->setIconSize(QSize(tmp_btn->size().width() , tmp_btn->size().height() ));
    tmp_btn->setAutoFillBackground(false);
    tmp_btn->setTaken(true);
    //    tmp_btn->setEnabled(false);
}


void GSquare::animation_victory()
{
    QPixmap pixmap("Victoire.png");
//    QGraphicsProxyWidget *wid = new QGraphicsProxyWidget(fond);
   QGraphicsPixmapItem *graph_pix = new QGraphicsPixmapItem(pixmap, fond, scene);
    graph_pix->setPos(400, 200);

}

void GSquare::button_released(QAbstractButton *sender)
{
    GCase *tmp_btn = (GCase *)sender;

    // TODO récupérer le resultat de l'ia
    JudgeDredd judge;
    coord_t coord;
    coord.x = tmp_btn->getX();
    coord.y = tmp_btn->getY();

    try
    {
		if (tmp_btn->isTaken() == false)
		{
			 judge.putPieceOnMap(info, coord);
			change_btn_state(tmp_btn);
			change_currentPlayer();
			MinMax ia;
			coord = ia.launch(info);
			judge.putPieceOnMap(info, coord);
			if ((tmp_btn = static_cast<GCase*>(group_pions->button(coord.x * 100 + coord.y))));
				change_btn_state(tmp_btn);
			change_currentPlayer();
		}
    }
    catch (GameExceptionWinByScore& e)
    {
        change_btn_state(tmp_btn);
        this->animation_victory();
    }
    catch (GameExceptionWinByAlignement& e)
    {
        change_btn_state(tmp_btn);
        this->animation_victory();
    }
    catch (const GameExceptionTwinTriple& e)
    {
        box.setText("Vous ne pouvez pas effectuer ce coup");
        box.setWindowTitle("Coup Interdit");
        box.exec();
        QTimer::singleShot(300, this, SLOT(end_of_box()));
    }
    catch (InvalidMapException e)
    {
//        box(this);
        box.setText("Exception InvalidMap");
        box.setWindowTitle("Coup Interdit");
        box.exec();
        QTimer::singleShot(300, this, SLOT(end_of_box()));
    }
    catch (GameInfo e)
    {
        //box(this);
        box.setText("Exception GameInfo");
        box.setWindowTitle("Coup Interdit");
        box.exec();
        QTimer::singleShot(300, this, SLOT(end_of_box()));
    }
    //afficher le résultat
    
}

void GSquare::end_of_box()
{
    box.close();
}


void GSquare::button_pressed(QAbstractButton *sender)
{
//    tmp_btn->backgroundRole()
}

